const express = require('express');
const cors = require('cors');

const app = express();

// 配置 CORS 选项
const corsOptions = {
  origin: 'http://localhost:3000', // 允许访问的前端地址
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true,               // 允许携带 Cookie
};

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); // 允许的来源
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');  // 允许的请求方法
    res.header('Access-Control-Allow-Headers', 'Content-Type');         // 允许的请求头
    res.header('Access-Control-Allow-Credentials', 'true');             // 允许携带 Cookie
    next();
  });

app.use(cors(corsOptions));

app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

app.listen(5000, () => {
  console.log('Server is running on http://localhost:5000');
});
